package com.crayfish.quduo.presenter;

import android.util.Log;

import com.crayfish.quduo.base.RxPresenter;
import com.crayfish.quduo.commom.Configs;
import com.crayfish.quduo.http.JokeItemResponse;
import com.crayfish.quduo.http.RetrofitHelper;
import com.crayfish.quduo.http.TianXinResponse;
import com.crayfish.quduo.model.BannerBean;
import com.crayfish.quduo.model.JokeItemBean;
import com.crayfish.quduo.model.LaiFuDaoBean;
import com.crayfish.quduo.model.MeipaiBean;
import com.crayfish.quduo.model.TianXinBean;
import com.crayfish.quduo.presenter.contract.MainContract;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by crayfish on 2016/12/9.
 */
public class MainPresenter extends RxPresenter<MainContract.View> implements MainContract.Presenter {

    private RetrofitHelper mRetrofitHelper;

    public MainPresenter(RetrofitHelper retrofitHelper){
        this.mRetrofitHelper = retrofitHelper;
    }
    @Override
    public void getMeipaiData(String id) {
        Subscription rxSubscription = mRetrofitHelper.getMeipaiList(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<MeipaiBean>>() {
                    @Override
                    public void call(List<MeipaiBean> meipaiBeens) {
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError("加载数据失败！");
                    }
                });
        addSubscribe(rxSubscription);
    }

    @Override
    public void getTupianData() {
        Subscription rxSubscription = mRetrofitHelper.getTupianList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<LaiFuDaoBean>>() {
                    @Override
                    public void call(List<LaiFuDaoBean> laiFuDaoBeen) {
                        mView.showContent(laiFuDaoBeen);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError("加载数据失败！");
                    }
                });
        addSubscribe(rxSubscription);
    }

    @Override
    public void getJokeData() {
//        Subscription rxSubscription = mRetrofitHelper.getJokeList("1","20","")
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .flatMap(new Func1<JokeItemResponse<JokeItemBean>, Observable<List<JokeItemBean.Item>>>() {
//                    @Override
//                    public Observable<List<JokeItemBean.Item>> call(final JokeItemResponse<JokeItemBean> jokeItemResponse) {
//                        if(jokeItemResponse.getShowapi_res_code() == 0){
//                            return Observable.create(new Observable.OnSubscribe<List<JokeItemBean.Item>>() {
//                                @Override
//                                public void call(Subscriber<? super List<JokeItemBean.Item>> subscriber) {
//                                    try {
//                                        subscriber.onNext(jokeItemResponse.getShowapi_res_body().getContentlist());
//                                        subscriber.onCompleted();
//                                    } catch (Exception e) {
//                                        subscriber.onError(e);
//                                    }
//                                }
//                            });
//                        }else{
//                            return Observable.error(new Exception("服务器返回error"));
//                        }
//                    }
//                })
//                .subscribe(new Action1<List<JokeItemBean.Item>>() {
//                    @Override
//                    public void call(List<JokeItemBean.Item> jokeItemBeen) {
//                        mView.showContents(jokeItemBeen);
//                    }
//                },new Action1<Throwable>(){
//                    @Override
//                    public void call(Throwable throwable) {
//                        mView.showError("加载数据失败！");
//                    }
//                });
//        addSubscribe(rxSubscription);
        //以上是接口获取,以下是bmob获取
        String SQL = "select * from Item ORDER by comment desc";
        BmobQuery<JokeItemBean.Item> query = new BmobQuery<>();
        query.setSQL(SQL);
        Log.d("SQL",SQL);
//        boolean isCache = query.hasCachedResult(JokeItemBean.Item.class);
//        if(isCache){
//            query.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
//        }else{
//            query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
//        }
        query.doSQLQuery(SQL, new SQLQueryListener<JokeItemBean.Item>() {
            @Override
            public void done(BmobQueryResult<JokeItemBean.Item> bmobQueryResult, BmobException e) {
                if(mView == null){
                    return;
                }
                if(e == null) {
                    mView.showContents(bmobQueryResult.getResults());
                }else {
                    mView.showError("加载数据失败！");
                }
            }
        });
    }

    @Override
    public void getMeinvData() {
        Subscription rxSubscription = mRetrofitHelper.getMeinvList("5","1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<TianXinResponse<List<TianXinBean>>, Observable<List<TianXinBean>>>() {
                    @Override
                    public Observable<List<TianXinBean>> call(final TianXinResponse<List<TianXinBean>> tianXinResponse) {
                        if(tianXinResponse.getCode() == 200){
                            return Observable.create(new Observable.OnSubscribe<List<TianXinBean>>() {
                                @Override
                                public void call(Subscriber<? super List<TianXinBean>> subscriber) {
                                    try {
                                        subscriber.onNext(tianXinResponse.getNewslist());
                                        subscriber.onCompleted();
                                    } catch (Exception e) {
                                        subscriber.onError(e);
                                    }
                                }
                            });
                        }else{
                            return Observable.error(new Exception("服务器返回error"));
                        }
                    }
                })
                .subscribe(new Action1<List<TianXinBean>>() {
                    @Override
                    public void call(List<TianXinBean> tianXinBeen) {
//                        mView.showBanner(tianXinBeen);
                    }
                },new Action1<Throwable>(){
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError("加载数据失败！");
                    }
                });
        addSubscribe(rxSubscription);
    }

    @Override
    public void getBannerData() {
        String SQL = "select * from banner";
        BmobQuery<BannerBean> query = new BmobQuery<>();
        query.setSQL(SQL);
        Log.d("SQL",SQL);
        boolean isCache = query.hasCachedResult(BannerBean.class);
        if(isCache){
            query.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
        }else{
            query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
        }
        query.doSQLQuery(SQL, new SQLQueryListener<BannerBean>() {
            @Override
            public void done(BmobQueryResult<BannerBean> bmobQueryResult, BmobException e) {
                if(mView == null){
                    return;
                }
                if(e == null) {
                    mView.showBanner(bmobQueryResult.getResults());
                }else {
                      mView.showError("加载数据失败！");
                }
            }
        });
    }
}
